package com.qfjy.controller;

import com.alibaba.fastjson2.JSON;
import com.qfjy.common.util.redis.RepeatUtil;
import com.qfjy.common.util.result.ResultCode;
import com.qfjy.common.util.result.ResultJson;
import com.qfjy.entity.po.User;
import com.qfjy.entity.utils.ExcelUtils;
import com.qfjy.entity.vo.UserVO;
import com.qfjy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Controller
@Slf4j
@CrossOrigin
@RequestMapping("/user")
@Api(tags = {"用户管理模块"})
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RepeatUtil repeatUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @ApiOperation(value = "查询所有的用户列表数据")
    @GetMapping("/list")
    @ResponseBody
    public ResultJson list() {
        List<User> list = userService.selectList();

        return new ResultJson(list, ResultCode.SUCCESS);
    }

    /**
     * todo 进入用户列表页面
     *
     * @return
     */
    @GetMapping("/listPage")
    public String listPage(HttpServletRequest request) {
        List<User> list = userService.selectList();
        request.setAttribute("list", list);

        return "user/list";
    }

    /**
     * todo 进入用户列表页面 列表按条件进行查询
     *
     * @return
     */
    @GetMapping("/listCondition")
    @ApiOperation(value = "列表按照条件进行查询")
    public String listCondition(HttpServletRequest request, UserVO userVO) {

        List<User> list = userService.listCondition(userVO);
        request.setAttribute("name", userVO.getName());
        request.setAttribute("rid", userVO.getRid());
        request.setAttribute("startTime", userVO.getStartTime());
        request.setAttribute("endTime", userVO.getEndTime());
        request.setAttribute("list", list);

        return "user/list";
    }

    /**
     * todo 进入Excel数据导入页面
     */
    @GetMapping("/importExcelToPage")
    public String importExcelToPage(HttpServletRequest request) {
        // 生成redis的token
        repeatUtil.generatorToken(request, "repeat:user:importExcel:");
        return "user/importExcel";
    }


    /**
     * todo Excel文件导入
     */
    @PostMapping("/importExcel")
    @ResponseBody
    public ResultJson importExcel(@RequestParam("file") MultipartFile file,
                                  HttpServletRequest request) {
        int num = 0;
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        if (!repeatUtil.validateToken(request, "repeat:user:importExcel:")) {
            // 不相等
            log.info("此次请求是重复请求-->");
        } else {
            // 第一次进来,进行添加
            try {

                // 解析Excel 工具类 解析导入
                List<User> list = ExcelUtils.importExcel(file, User.class);

                // 使用Stream API进行去重处理，根据email字段去重
                List<User> distinctUsers = list.stream()
                        .collect(Collectors.toMap(User::getEmail, Function.identity(), (existing, replacement) -> existing))
                        .values().stream()
                        .collect(Collectors.toList());

                //批量添加到MYSQL数据库
                num = userService.insertBatchUsers(distinctUsers);

                log.info("导入成功,{}", list.size());
                return new ResultJson(num, ResultCode.SUCCESS);
            } catch (IOException e) {
                log.error("Excel导入异常" + e.getMessage());
            }
        }
        return new ResultJson(num, ResultCode.FAIL);
    }

    /**
     * todo 导出功能 Excel(根据列表查询的条件后)
     */
    @RequestMapping("/exportExcelCondition")
    public void exportExcelCondition(HttpServletRequest request, UserVO userVO, HttpServletResponse response) throws IOException {
        List<User> list = userService.listCondition(userVO);
        ExcelUtils.exportExcel(list, "智慧会议用户信息列表", "用户信息列表", User.class, "智慧会议用户信息列表", response);

    }


    /**
     * todo 单行删除
     */
    @PostMapping("/deleteById")
    @ResponseBody
    public ResultJson deleteById(@RequestParam("id") final Integer id) {
        int num = userService.deleteById(id);
        log.info("根据ID进行删除:{}", num);

        return new ResultJson(num, ResultCode.SUCCESS);
    }

    /***
     * todo 批量删除
     */
    @PostMapping("/deleteBatch")
    @ResponseBody
    public ResultJson deleteBatch(@RequestParam("ids[]") Integer[] ids) {
        int num = userService.deleteBatch(ids);

        if (num > 0) {
            log.info("批量删除成功{}", num);
            return new ResultJson<>(num, ResultCode.SUCCESS);
        }

        return new ResultJson(num, ResultCode.FAIL);
    }

    /**
     * todo 更改状态
     */
    @GetMapping("/updateStatusById")
    @ResponseBody
    public ResultJson updateStatusById(@RequestParam("status") int status, @RequestParam("id") int id) {
        int num = userService.updateUserStatusById(status, id);

        return new ResultJson(num, ResultCode.SUCCESS);
    }
}



